package com.ytjj.qmyx.supplychain.api.controller;

import com.alibaba.excel.util.CollectionUtils;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.ReturnOrderStatisticsResponse;
import com.ytjj.qmyx.supplychain.common.model.request.ReturnGoodsQueryRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ReturnGoodsRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ReturnOrderStatisticsRequest;
import com.ytjj.qmyx.supplychain.common.model.response.ReturnGoodsQueryResponse;
import com.ytjj.qmyx.supplychain.mapper.ExpressOrdersMapper;
import com.ytjj.qmyx.supplychain.mapper.ReturnGoodsMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import com.ytjj.qmyx.supplychain.service.ReturnGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 售后管理
 */
@Slf4j
@RestController
@RequestMapping("/returnGoods")
public class ReturnGoodsController {

    @Autowired
    private ReturnGoodsService returnGoodsService;
    @Resource
    private ExpressOrdersMapper expressOrdersMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    /**
     * 快递更新时间差值 30分钟
     */
    private static final long DIFFERENCE_VALUE = 1800L;

    /**
     * 售后数据上传
     * @param yxReturnGoods
     * @return
     */
    @PostMapping("/returnGoodsUpload")
    public CommonResult returnGoodsUpload(@RequestBody YxReturnGoods yxReturnGoods) {
        return returnGoodsService.returnGoodsUpload(yxReturnGoods);
    }

    /**
     * 售后数据上传--供团购渠道调用
     * @param yxReturnGoods
     * @return
     */
    @PostMapping("/returnGoodsUploadFromTuan")
    public CommonResult returnGoodsUploadFromTuan(@RequestBody YxReturnGoods yxReturnGoods) {
        return returnGoodsService.returnGoodsUploadFromTuan(yxReturnGoods);
    }

    /**
     * 修改售后状态
     */
    @PostMapping("/updateReturnGoods")
    public CommonResult updateReturnGoods(@RequestBody YxReturnGoods yxReturnGoods) {
        return returnGoodsService.updateReturnGoods(yxReturnGoods);
    }

    /**
     * 修改售后类型
     */
    @PostMapping("/updateReturnGoodsType")
    public CommonResult updateReturnGoodsType(@RequestBody YxReturnGoods yxReturnGoods) {
        return returnGoodsService.updateReturnGoodsType(yxReturnGoods);
    }

    /**
     * 查询售后订单信息
     * @param request
     * @return
     */
    @PostMapping("/queryReturnGoods")
    public List<ReturnGoodsQueryResponse> queryReturnGoods(@RequestBody ReturnGoodsQueryRequest request){
        return returnGoodsService.queryReturnGoods(request);
    }

    /**
     * 查询供应商收货地址
     */
    @GetMapping("/getReturnGoodAddress")
    public CommonResult getReturnGoodAddress(@RequestParam(value = "bankerId") Integer bankerId,
                                             @RequestParam(value = "addressId",required = false) Integer addressId) {
        log.info("===bankerId==={}", bankerId);
        System.out.println("======bankerId=" + bankerId + "===========");
        return CommonResult.success(returnGoodsService.getReturnGoodAddress(bankerId,addressId));
    }

    /**
     * 查询多个供应商收货地址
     */
    @GetMapping("/getReturnGoodAddressList")
    public CommonResult getReturnGoodAddressList(@RequestParam("bankerIds") String bankerIds) {
        return CommonResult.success(returnGoodsService.getReturnGoodAddressList(bankerIds));
    }

    /**
     * 快递流水
     */
    @GetMapping("/getLogisticsOld")
    public CommonResult getLogisticsOld(@RequestParam String tel, @RequestParam String expressCompany, @RequestParam String expressNo) {
        if (tel != null && expressCompany != null && expressNo != null) {
            Example example = new Example(YxExpressOrders.class);
            example.createCriteria().andEqualTo("companyNo", expressCompany).andEqualTo("expressEno", expressNo);
            example.orderBy("updateTime").desc();
            List<YxExpressOrders> list = expressOrdersMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(list)) {
                return CommonResult.success("暂无物流信息！");
            }
            return CommonResult.success(list.get(0).getInfoText());
        } else {
            return CommonResult.success("暂无物流信息！");
        }
    }

    /**
     * 退货快递流水(这里改成查退款表数据)
     */
    @GetMapping("/getLogistics")
    public CommonResult getLogistics(String tel,String expressCompany,String expressNo) {
        if (StringUtils.isNotBlank(expressCompany) && StringUtils.isNotBlank(expressNo)) {
            Example example = new Example(YxReturnGoods.class);
            example.createCriteria().andEqualTo("returnExpressCompany", expressCompany).andEqualTo("returnExpressNo", expressNo);
            List<YxReturnGoods> list = returnGoodsMapper.selectByExample(example);
            List<QueryTrackData> queryTrackData = new ArrayList<>();
            if (list.size() >= 1) {
                YxReturnGoods yxReturnGoods = list.get(0);
                QueryTrackResp queryTrackResp = returnGoodsService.dealReturnTrack(yxReturnGoods);
                if ("200".equals(queryTrackResp.getStatus())) {
                    queryTrackData = queryTrackResp.getData();
                } else {
                    if (StringUtils.isNotBlank(queryTrackResp.getReturnCode()) && !"500".equals(queryTrackResp.getReturnCode())) {
                        throw new ApiException(queryTrackResp.getMessage());
                    }
                }
            }
            return CommonResult.success(queryTrackData);
        } else {
            return CommonResult.success("暂无物流信息！");
        }
    }

    /**
     * 创建售后地址
     */
    @PostMapping("/insertAddress")
    public String insertAddress(@RequestBody YxBankerStoreAddress yxBankerStoreAddress) {
        yxBankerStoreAddress.setId(null);
        return returnGoodsService.insertAddress(yxBankerStoreAddress);
    }

    /**
     * 修改供应商商品售后地址
     */
    @GetMapping("/updateBankerProductAddressId")
    public CommonResult updateBankerProductAddressId(@RequestParam String bankerProductId,@RequestParam String addressId){
        return returnGoodsService.updateBankerProductAddressId(Integer.valueOf(bankerProductId),Integer.valueOf(addressId));
    }

    @PostMapping("/selectReturnGoodsList")
    public CommonPage selectReturnGoodsList(@RequestBody ReturnGoodsRequest request) {
        return returnGoodsService.selectReturnGoodsList(request);
    }

    /**
    * 退货管理列表接口
    */
    @PostMapping("/selectReturnGoods")
    public CommonResult selectReturnGoods(@RequestBody ReturnGoodsRequest request) {
        return CommonResult.success(returnGoodsService.selectAllList(request));
    }

    @GetMapping("/getDetailById")
    public CommonResult getReturnGoodsDetail(@RequestParam Integer id) {
        return returnGoodsService.getReturnGoodsDetailInfo(id);
    }

    @GetMapping("/getDetailByServiceNo")
    public CommonResult getReturnGoodsDetail(@RequestParam(required = false) String serviceNo,
                                             @RequestParam(required = false) String mergeNo) {
        return returnGoodsService.getReturnGoodsDetailInfoByServiceNo(serviceNo,mergeNo);
    }

    @GetMapping("/deleteReturnGoods")
    public Integer deleteReturnGoods(@RequestParam(required = false) String serviceNo,
                                     @RequestParam(required = false) String mergeNo,
                                     @RequestParam(required = false) String orderInfoStatus) {
        return returnGoodsService.deleteReturnGoods(serviceNo,mergeNo,orderInfoStatus);
    }

    /**
     * 客服撤销售后
     * @param serviceNo
     * @param mergeNo
     * @param orderInfoStatus
     * @return
     */
    @GetMapping("/removeReturnGoods")
    public Integer removeReturnGoods(@RequestParam(required = false) String serviceNo,
                                     @RequestParam(required = false) String mergeNo,
                                     @RequestParam(required = false) String orderInfoStatus) {
        return returnGoodsService.removeReturnGoods(serviceNo,mergeNo,orderInfoStatus);
    }

    /**
     * 检查跨境订单是否能申请售后
     * @param yxReturnGoods childOrderNo()=子订单号 bankerId=供应商id  userId=用户id
     * @return 1=能  0=不能
     */
    @PostMapping("/checkAbroadOrderCancel")
    public CommonResult checkAbroadOrderCancel(@RequestBody YxReturnGoods yxReturnGoods) {
        if (StringUtils.isEmpty(yxReturnGoods.getChildOrderNo()) || null == yxReturnGoods.getBankerId() || null == yxReturnGoods.getUserId()) {
            return CommonResult.failed("参数错误！");
        }
        boolean result = returnGoodsService.abroadOrderCancelCheck(yxReturnGoods);
        return result ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 执行单品售后统计
     */
    @PostMapping("/doProductRefundStatistics")
    public CommonResult doProductRefundStatistics(@RequestBody ReturnOrderStatisticsRequest orderStatisticsResponses) {
        Integer integer = returnGoodsService.doProductRefundStatistics(orderStatisticsResponses);
        return integer > 0 ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 单品退款统计的-回调接口
     */
    @PostMapping("/recordRefundOrderCallback/{markId}")
    public CommonResult statisticsReturnOrder(@PathVariable String markId, @RequestBody List<ReturnOrderStatisticsResponse> orderStatisticsResponses) {
        returnGoodsService.statisticsReturnOrder(markId, orderStatisticsResponses);
        return CommonResult.success();
    }

    /**
     * 单品退单统计-统计详情
     */
    @GetMapping("/getProductRefundStatisticsDetail")
    public CommonResult<CommonPage<ReturnGoodStatisticsDetail>> getProductRefundStatisticsDetail(String markId,Integer pageNum,Integer pageSize) {
        CommonPage<ReturnGoodStatisticsDetail> statisticsReturnDetail = returnGoodsService.getProductRefundStatisticsDetail(markId, pageNum, pageSize);
        return CommonResult.success(statisticsReturnDetail);
    }

    /**
     * 单品退单统计-统计详情汇总
     */
    @GetMapping("/getProductRefundStatisticsSummary")
    public CommonResult<ReturnGoodStatisticsDetail> getProductRefundStatisticsSummary(String markId) {
        ReturnGoodStatisticsDetail statisticsReturnDetail = returnGoodsService.getProductRefundStatisticsSummary(markId);
        return CommonResult.success(statisticsReturnDetail);
    }


    /**
     * 分页查询退款订单的统计历史
     */
    @GetMapping("/getHistoryProductRefund")
    public CommonResult<CommonPage<ReturnGoodStatisticsSearch>> getHistoryProductRefund(Integer pageNum, Integer pageSize) {
        CommonPage<ReturnGoodStatisticsSearch> page = returnGoodsService.getHistoryProductRefund(pageNum, pageSize);
        return CommonResult.success(page);
    }


}
